package com.yubest.springboothello.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.system.ApplicationPid;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;

/**
 * @Author: hweiyu
 * @Date: 2024/8/15 14:47
 */
@Component
@Slf4j
public class PidConfig implements ApplicationRunner {

    @Value("${spring.application.name}")
    private String applicationName;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        new Thread(() -> {
            try {
                File pidFile = new File(applicationName + ".pid");
                new ApplicationPid().write(pidFile);
                pidFile.deleteOnExit();
            } catch (IOException e) {
                log.error("获取应用 Pid 异常", e);
            }
        }).start();
    }
}
